<?php

namespace app\cash\controller;

use app\BaseController;
use app\beautiful\model\member\MemberModel;
use app\beautiful\model\order\OrderRefundModel;
use app\beautiful\model\setting\TableNumberModel;
use app\cash\model\CartModel;
use app\cash\model\CashJointTableModel;
use app\cash\model\CashSettleInfoModel;
use app\cash\model\CashThirdsettleModel;
use app\cash\model\GuaBillModel;
use app\cash\model\OpenTableModel;
use app\common\logic\SmsLogic;
use app\stores\logic\LogsLogic;
use app\stores\logic\MemberWalletLogic;
use app\stores\logic\order\OrderLogic;
use app\stores\model\cash\ThirdSettlementModel;
use app\stores\model\order\GoodsOrderModel;
use think\facade\Cache;
use think\facade\Db;

class Order extends BaseController{
    /**
     * 落单
     */
    public function confirmOrder(){
        $table_number_id = $this->request->param('table_number_id/d',0);
        $member_id = $this->request->param('member_id/d',0);
        $is_fit = $this->request->param('is_fit/d',0);
        $origin_type = $this->request->param('origin_type/d',2);
        $remarks = $this->request->param('remarks');
        $service_type = $this->request->param('service_type/d',1);//开台过来的传1）就餐方式：1堂食2打包3外卖
        Db::startTrans();
        try{
            $list = [];
            $where['origin_type'] = $origin_type;
            $where['shop_id'] = $this->request->shopId;
            $where['is_delete'] = 0;
            $where_in[] = ['status','in',[0,2]];
            if($table_number_id){
                $where['table_number_id'] = $table_number_id;
                $list = CartModel::list($where,$where_in);
                if(empty($list))  return $this->error('不需要落单');
                CartModel::up(['status'=>1],$where);
            }else{
                if($is_fit){
                    if($table_number_id<1) $where['account_id'] = $this->request->accountId;
                    $where['table_number_id'] = $table_number_id>0?$table_number_id:0;
                    $where['member_id'] = 0;
                    $where['is_fit'] = $is_fit;
                    $list = CartModel::list($where,$where_in);
                    if(empty($list))  return $this->error('不需要落单');
                    CartModel::up(['status'=>1],$where);
                }
                if($member_id){
                    $where['member_id'] = $member_id;
                    $where['table_number_id'] = 0;
                    $where['is_fit'] = 0;
                    $list = CartModel::list($where,$where_in);
                    if(empty($list))  return $this->error('不需要落单');
                    CartModel::up(['status'=>1],$where);
                }
            }

            if($list) {
                foreach ($list as $k => $v) {
                    //修改落单数量
                    CartModel::up(['confirm_num'=>$v['num']],['cart_id'=>$v['cart_id']]);
                    //未落单数(打印需要用到)
                    $un_num = $v['num'] - $v['confirm_num'];
//                    $goods = \app\cash\model\GoodsModel::info(['goods_id' => $v['goods_id'], 'shop_id' => $this->request->shopId, 'origin_type' => 2, 'is_delete' => 0]);
//                    if ($goods) {
//                        //
//
//                        if (in_array($order->logistics_type, [1, 2, 3])) {
//                            //判断是否有分区打印的产品
//                            $return_goods_produce = goodsProduce($orderId);
//                            $prints = $return_goods_produce['prints'];
//                            $produce_printer_ids = [];
//                            if ($prints) {
//                                $printer_logic = new \app\stores\logic\printer\PrinterLogic($order->shop_id);
//                                $produce_printer_ids = $printer_logic->producePrint($type, $orderId, $prints);
//                            }
//                            //原来的打印排除已分区打印的打印机
//                            $printer_logic = new PrinterLogic($order->shop_id);
//                            $printer_logic->print($type, $orderId, $produce_printer_ids);
//
//                        }
//                    }
                }
            }



            Db::commit();

            return $this->success('落单成功');

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
    }
    /**
     *挂单(只有落单后的才能挂单、散客不能挂单,挂单、挂账和order_id对应-》即购物车添加order_id字段。挂单用户小程序买单，挂账只能在收银台买单)
     */
    public function guaOrder(){
        $table_number_id = $this->request->param('table_number_id/d',0);
        $member_id = $this->request->param('member_id/d',0);
        //$total_price = $this->request->param('total_price/f',0);
        $origin_type = $this->request->param('origin_type/d',1);

        if($table_number_id<1 && $member_id<1) return $this->error('用户信息必传');

        $list = [];
        $where['origin_type'] = $origin_type;
        $where['shop_id'] = $this->request->shopId;
        $where['status'] = 1;
        $where['is_delete'] = 0;

        Db::startTrans();
        try{
            if($table_number_id){
                $ot = OpenTableModel::getById(['table_number_id'=>$table_number_id,'status'=>0,'shop_id'=>$this->request->shopId,'is_delete'=>0]);
                if($ot['member_id']<1) return $this->error('散客不能挂单');
                $where['table_number_id'] = $table_number_id;
                $where['member_id'] = $ot['member_id'];
                $where['is_fit'] = 0;
                $list = CartModel::list($where);
            }
            if($table_number_id<1 && $member_id>0){
                $where['member_id'] = $member_id;
                $where['table_number_id'] = 0;
                $where['is_fit'] = 0;
                $list = CartModel::list($where);
            }

            if(empty($list)) return $this->error('没有数据');

            $data['member_id'] = $member_id;
            //$data['total_price'] = $total_price;
            $data['use_integral'] = 0;
            $data['coupon_id'] = 0;
            $data['is_gua_order'] = 1;
            $order_id = $this->createOrder($list,$data);

            //修改购物车
            CartModel::up(['order_id'=>$order_id],$where);

            //推送
            if($order_id){
                $count = GoodsOrderModel::where(['shop_id'=>$this->request->shopId,'status'=>16])->count();
                $s_data['data']['gua_order_count'] = $count;
                $s_data['type'] = 'gua_order';
                pushWebsocket($this->request->shopId,$this->request->accountId,$s_data);

            }

            Db::commit();

            return $this->success(['order_id'=>$order_id]);
        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
    }
    /**
     * 挂账（散客可以挂账，和order_id对应-》即购物车添加order_id字段。挂单用户小程序买单，挂账只能在收银台买单）
     */
    public function guaBill(){
        $order_id = $this->request->param('order_id/d',0);
        $member_name = $this->request->param('member_name');
        $member_mobile = $this->request->param('member_mobile');
        $gua_bill_reason = $this->request->param('gua_bill_reason');

        if(empty($member_name)) return $this->error('客户名称不能为空');
        if(empty($member_mobile)) return $this->error('手机号码不能为空');

        $order = GoodsOrderModel::where(['shop_id'=>$this->request->shopId,'order_id'=>$order_id])->find();
        if(empty($order)) return $this->error('订单不存在');
        if($order['status']!=1) return $this->error('该订单不能挂账');

        $order->status = 15;
        $order->save();

        $data['order_id'] = $order_id;
        $data['shop_id'] = $this->request->shopId;
        $data['member_name'] = $member_name;
        $data['member_mobile'] = $member_mobile;
        $data['reason'] = $gua_bill_reason;
        GuaBillModel::insertGetId($data);

        return $this->success('挂账成功');
    }
    //生成订单
    function createOrder($list,$data)

    {
        $params=[
            'shop_id'=>$this->request->shopId,

            'member_id'=>$data['member_id'],

            'goods'=>$list,

            //'total_price'=>$data['total_price'],

            'from_type'=>3,

            'is_gua_order'=>isset($data['is_gua_order'])?$data['is_gua_order']:0,

            'coupon_id'=>isset($data['coupon_id'])?$data['coupon_id']:0,

            'use_integral'=>isset($data['use_integral'])?$data['use_integral']:0,

            'open_table_id'=>isset($data['open_table_id'])?$data['open_table_id']:0,
        ];

        $order_logic = OrderLogic::init($this->request->shopId);

        $order_id = $order_logic['cash']->createOrder($params);


        return $order_id;



    }

    //打印
    public function print(){
        //1预结单()2结账单3消费单4订单明细5消费单（无桌号堂食）6制作单7退菜单8崔菜单9换台单10并台单11传菜单12转菜单13点菜单14点菜单（打包、外卖）15制作单（无桌号）
        $type = $this->request->param('type/d',0);
        if($type==1){

        }
    }
    /**
     * 结账(生成订单，挂单和挂账改变订单状态)（以主台用户为准，扣除主台用户余额）
     */
    public function payOrder(){
        $table_number_id = $this->request->param('table_number_id/d',0);
        $member_id = $this->request->param('member_id/d',0);
        $is_fit = $this->request->param('is_fit/d',0);
        $order_id= $this->request->param('order_id/d',0);
        $origin_type = $this->request->param('origin_type/d',2);
        //以生成订单的不用在生成
        if($order_id){
            $order = GoodsOrderModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'is_delete'=>0])->find();
            if(empty($order)) return $this->error('订单不存在');
            return $this->success(['order_id'=>$order_id]);
        }

        if($table_number_id<1 && $is_fit<1 && $member_id<1) return $this->error('用户信息必传');

        $table_number_ids = [];
        //查找该桌台是否被并台或联台
        if($table_number_id>0){
            //联台
            //主
            $liantai_table_number_ids = CashJointTableModel::where(['shop_id'=>$this->request->shopId,'master_table_number_id'=>$table_number_id,'status'=>0,'is_joint_order'=>1,'type'=>2,'is_delete'=>0])->column('table_number_id');
            if($liantai_table_number_ids){
                $table_number_ids = $liantai_table_number_ids;
                $table_number_ids[] = $table_number_id;
            }else{
                //次
                $liantai_joint = CashJointTableModel::where(['shop_id'=>$this->request->shopId,'table_number_id'=>$table_number_id,'status'=>0,'is_joint_order'=>1,'type'=>2,'is_delete'=>0])->find();
                if($liantai_joint){
                    $liantai_table_number_ids = CashJointTableModel::where(['shop_id'=>$this->request->shopId,'master_table_number_id'=>$liantai_joint['master_table_number_id'],'status'=>0,'is_joint_order'=>1,'type'=>2,'is_delete'=>0])->column('table_number_id');
                    $table_number_ids = $liantai_table_number_ids;
                    $table_number_ids[] = $liantai_joint['master_table_number_id'];
                }
            }

            //并台
            $have_master_joint = CashJointTableModel::where(['shop_id'=>$this->request->shopId,'master_table_number_id'=>$table_number_id,'status'=>0,'type'=>1,'is_delete'=>0])->column('table_number_id');
            $have_joint = CashJointTableModel::info(['shop_id'=>$this->request->shopId,'table_number_id'=>$table_number_id,'status'=>0,'type'=>1,'is_delete'=>0]);
            if($have_master_joint){
                $table_number_ids = $have_master_joint;
                $table_number_ids[] = $table_number_id;
            }
            if($have_joint){
                $table_number_ids = CashJointTableModel::where(['shop_id'=>$this->request->shopId,'master_table_number_id'=>$have_joint['master_table_number_id'],'status'=>0,'type'=>1,'is_delete'=>0])->column('table_number_id');
                $table_number_ids[] = $have_joint['master_table_number_id'];
            }
        }
        if(empty($table_number_ids) && $table_number_id) $table_number_ids[] = $table_number_id;
        $where = $list = [];
        $where['origin_type'] = $origin_type;
        $where['shop_id'] = $this->request->shopId;
        $where['is_delete'] = 0;
        if($table_number_id<1) $where['account_id'] = $this->request->accountId;
        Db::startTrans();
        try{
            //有桌台或有桌台并联台、并台
            if($table_number_ids){
                for($i=0;$i<count($table_number_ids);$i++){
                    $table = TableNumberModel::info(['shop_id'=>$this->request->shopId,'id'=>$table_number_ids[$i]]);
                    $ot = OpenTableModel::getById(['table_number_id'=>$table_number_ids[$i],'status'=>0,'shop_id'=>$this->request->shopId,'is_delete'=>0]);
                    if(empty($ot)) return $this->error('桌台'.$table['name'].'已结束');

                    $where['table_number_id'] = $table_number_ids[$i];
                    $where['member_id'] = $ot['member_id'];
                    $where['is_fit'] = $ot['is_fit'];
                    $lists[$i] = CartModel::list($where);
                    if(empty($lists[$i])) return $this->error('桌台'.$table['name'].'没有数据');

                    //是否存在未落单的数据
                    $c_where = $where;
                    $where_in[] = ['status','in',[0,2]];
                    $un_confirm = CartModel::list($c_where,$where_in);
                    if($un_confirm) return $this->error('桌台'.$table['name'].'未落单');

                    $list = array_merge($list,$lists[$i]);
                    $open_table_ids[] = $ot['open_table_id'];
                }
                $data['open_table_id'] = $open_table_ids;
            }else{
                //有开台
                if($table_number_id){
                    $ot = OpenTableModel::getById(['table_number_id'=>$table_number_id,'status'=>0,'shop_id'=>$this->request->shopId,'is_delete'=>0]);
                    $where['table_number_id'] = $table_number_id;
                    $where['member_id'] = $ot['member_id'];
                    $where['is_fit'] = $ot['is_fit'];
                    $list = CartModel::list($where);

                    $data['open_table_id'] = $ot['open_table_id'];
                }else{
                    //无开台不是散客
                    if($member_id){
                        $where['member_id'] = $member_id;
                        $where['table_number_id'] = 0;
                        $where['is_fit'] = 0;
                        $list = CartModel::list($where);
                    }else{
                        $where['member_id'] = 0;
                        $where['table_number_id'] = 0;
                        $where['is_fit'] = 1;
                        $list = CartModel::list($where);
                    }
                }
            }
            //是否存在未落单的数据
            $c_where = $where;
            $where_in[] = ['status','in',[0,2]];
            $un_confirm = CartModel::list($c_where,$where_in);

            if($un_confirm) return $this->error('还有未落单数据');

            if(empty($list)) return $this->error('没有数据');

            $data['member_id'] = $member_id;

            $order_id = $this->createOrder($list,$data);

            //修改购物车
            $cart_id = array_column($list,'cart_id');
            $update_cart_where[] = ['cart_id','in',$cart_id];
            CartModel::up(['order_id'=>$order_id],$update_cart_where);

            Db::commit();

            return $this->success(['order_id'=>$order_id]);

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
    }
    /**
     * 结账信息
     */
    public function getPayOrder(){
        $order_id = $this->request->param('order_id/d',0);

        if($order_id<1) return $this->error('订单不存在');

        $order = GoodsOrderModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'is_delete'=>0])->find();

        if(empty($order)) return $this->error('订单不存在');

        //桌台信息
        $order['table_name'] = $order['region_name'] = '';

        if($order['open_table_id']){

            $table_number_ids = explode(',',$order['open_table_id']);

            $open_table_ids = OpenTableModel::where(['shop_id'=>$this->request->shopId,'status'=>0,'is_delete'=>0])->whereIn('table_number_id',$table_number_ids)->column('open_table_id');
            //有并台或联台
            $field = 'n.name as table_name,r.name as region_name,r.id as region_id';

            $open_table_return = OpenTableModel::list(['shop_id'=>$this->request->shopId,'is_delete'=>0,'open_table_ids'=>$open_table_ids],[],$field);

            $order['table_info'] = $open_table_return['olist'];
        }
        //判断是否有未落单
        $c_where[] = ['shop_id','=',$this->request->shopId];
        $c_where[] = ['order_id','=',$order_id];
        $c_where[] = ['status','in',[0,2]];
        $c_where[] = ['is_delete','=',0];
        $un_confirm = CartModel::getCart($c_where);
        if(!empty($un_confirm)) return $this->error('还有未落单数据');
        //已付
        $total_pay_money = CashSettleInfoModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'info_type'=>1,'is_delete'=>0])->sum('money');
        $refund_money = CashSettleInfoModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'info_type'=>1,'is_delete'=>0])->sum('refund_money');
        $pay_money = $total_pay_money - $refund_money;
        //优惠
        $youhui_price = CashSettleInfoModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'info_type'=>2,'is_delete'=>0])->sum('money');
        $un_pay_money = sprintf("%.2f",$order['need_pay'] - $pay_money - $youhui_price);
        $order['pay_money'] = sprintf("%.2f",$pay_money);
        $order['un_pay_money'] = $un_pay_money<0?0:$un_pay_money;
        $order['youhui_price'] = sprintf("%.2f",$youhui_price);

        $where['shop_id'] = $this->request->shopId;
        $where['order_id'] = $order_id;

        $field = 'si.settle_info_id,si.type,si.name,si.num,si.money,si.refund_money,s.settlement_name';
        $px = ['si.add_time'=>'asc'];
        $return = CashSettleInfoModel::list($where,$px,0,0,$field);
        $order['settle_info'] = $return['list'];
        return $this->success($order);

    }
    /**
     * 扣除储值卡余额
     */
    public function deductMoney(){
        $order_id = $this->request->param('order_id/d',0);
        $money = $this->request->param('money/f',0);

        if($order_id<1) return $this->error('订单不存在');

        $order = GoodsOrderModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'is_delete'=>0])->find();
        if(empty($order)) return $this->error('订单不存在');
        if($order->status == 8) return $this->error('订单已完结');

        $member = MemberModel::where(['member_id'=>$order['member_id']])->find();

        if(empty($member)) return $this->error('用户不存在');

        //判断应付金额小于等于0时不用再支付了
        //已付
        $total_pay_money = CashSettleInfoModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'info_type'=>1,'is_delete'=>0])->sum('money');
        $refund_money = CashSettleInfoModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'info_type'=>1,'is_delete'=>0])->sum('refund_money');
        $pay_money = $total_pay_money - $refund_money;
        //优惠
        $youhui_price= CashSettleInfoModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'info_type'=>2,'is_delete'=>0])->sum('money');
        $un_pay_money = $order['need_pay'] - $pay_money - $youhui_price;
        if($un_pay_money<=0) return $this->error('没有未付金额了');

        Db::startTrans();

        try{
            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $order['member_id']);

            $res = $MemberWalletLogic->useBalance($money, $money, 26);

            if($res == false){

                Db::rollback();

                return $this->error($MemberWalletLogic->getError());
            }
            //结算信息
            $data = [
                'shop_id'=>$this->request->shopId,
                'order_id'=>$order_id,
                'name' => '储钱卡支付',
                'money' => $money,
                'num' => 1,
                'type' => 2,
                'info_type' => 1,
                'operate_id'=>$this->request->accountId,
                'add_ip'=>request()->ip()
            ];

            CashSettleInfoModel::insertGetId($data);

            Db::commit();

            return $this->success('支付成功');

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());
        }

        return $this->success($order);

    }
    /**
     * 扣除钱包余额
     */
    public function deductPlatformMoney(){
        $order_id = $this->request->param('order_id/d',0);
        $money = $this->request->param('money/f',0);
        $code = $this->request->param('code');

        if($order_id<1) return $this->error('订单不存在');

        $order = GoodsOrderModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'is_delete'=>0])->find();
        if(empty($order)) return $this->error('订单不存在');
        if($order->status == 8) return $this->error('订单已完结');

        $member = MemberModel::where(['member_id'=>$order['member_id']])->find();

        if(empty($member)) return $this->error('用户不存在');

        if($member['money']<$money) return $this->error('用户钱包余额不足');

        $cacheCode=Cache::get('useMoneyCode_'.$member['mobile']);

        if(empty($code) || $code!=$cacheCode){
            return $this->error('验证码错误！请重新输入');
        }

        //判断应付金额小于等于0时不用再支付了
        //已付
        $total_pay_money = CashSettleInfoModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'info_type'=>1,'is_delete'=>0])->sum('money');
        $refund_money = CashSettleInfoModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'info_type'=>1,'is_delete'=>0])->sum('refund_money');
        $pay_money = $total_pay_money - $refund_money;
        //优惠
        $youhui_price= CashSettleInfoModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'info_type'=>2,'is_delete'=>0])->sum('money');
        $un_pay_money = $order['need_pay'] - $pay_money - $youhui_price;
        if($un_pay_money<=0) return $this->error('没有未付金额了');

        Db::startTrans();
        try{

            $StoresMemberWalletLogic = new \app\stores\logic\MemberWalletLogic($this->request->shopId, $order['member_id']);

            $res = $StoresMemberWalletLogic->usePlatformMoney($money, 0,$order_id,0,26);

            if($res == false){

                Db::rollback();

                return $this->error($StoresMemberWalletLogic->getError());
            }
            //结算信息
            $data = [
                'shop_id'=>$this->request->shopId,
                'order_id'=>$order_id,
                'name' => '钱包支付',
                'money' => $money,
                'num' => 1,
                'type' => 3,
                'info_type' => 1,
                'operate_id'=>$this->request->accountId,
                'add_ip'=>request()->ip()
            ];

            CashSettleInfoModel::insertGetId($data);

            Db::commit();

            return $this->success('钱包支付成功');

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());
        }
    }
    /**
     * 现金（现金金额只能大于等于未付金额，不能随便输）
     */
    public function money(){
        $order_id = $this->request->param('order_id/d',0);
        $money = $this->request->param('money/f',0);

        if($order_id<1) return $this->error('订单不存在');
        $order = GoodsOrderModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'is_delete'=>0])->find();
        if(empty($order)) return $this->error('订单不存在');
        if($order->status == 8) return $this->error('订单已完结');

        //已付
        $total_pay_money = CashSettleInfoModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'info_type'=>1,'is_delete'=>0])->sum('money');
        $refund_money = CashSettleInfoModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'info_type'=>1,'is_delete'=>0])->sum('refund_money');
        $pay_money = $total_pay_money - $refund_money;
        //优惠
        $youhui_price= CashSettleInfoModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'info_type'=>2,'is_delete'=>0])->sum('money');
        //未支付
        $un_pay_money = sprintf("%.2f",$order['need_pay'] - $pay_money - $youhui_price);

        if($un_pay_money<=0) return $this->error('没有未付金额了');

        if($money<$un_pay_money) return $this->error('金额不能小于未付金额');

        $give_money = $money - $un_pay_money;

        if($money>$un_pay_money) $money = $un_pay_money;

        //结算信息
        $data = [
            'shop_id'=>$this->request->shopId,
            'order_id'=>$order_id,
            'name' => '现金支付',
            'money' => $money,
            'give_money'=> $give_money,
            'num' => 1,
            'type' => 6,
            'info_type' => 1,
            'operate_id'=>$this->request->accountId,
            'add_ip'=>request()->ip()
        ];

        CashSettleInfoModel::insertGetId($data);

        return $this->success('现金支付成功');
    }
    /**
     * 添加三方营销
     */
    public function addThirdSettle(){
        $order_id = $this->request->param('order_id/d',0);
        $third_settlement_id = $this->request->param('third_settlement_id/d',0);
        $num = $this->request->param('num/d',1);
        $remarks = $this->request->param('remarks');

        if($third_settlement_id<1) return $this->error('三方结算不存在');

        if($order_id<1) return $this->error('订单不存在');
        $order = GoodsOrderModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'is_delete'=>0])->find();
        if(empty($order)) return $this->error('订单不存在');
        if($order->status == 8) return $this->error('订单已完结');

        Db::startTrans();
        try{
            $third_settlement = ThirdSettlementModel::info(['third_settlement_id'=>$third_settlement_id,'shop_id'=>$this->request->shopId,'is_delete'=>0]);
            if(empty($third_settlement)) return $this->error('三方结算不存在');
            $cts_data['shop_id'] = $this->request->shopId;
            $cts_data['third_settlement_id'] = $third_settlement_id;
            $cts_data['settlement_type'] = $third_settlement['settlement_type'];
            $cts_data['settlement_name'] = $third_settlement['settlement_name'];
            $cts_data['par_value'] = $third_settlement['par_value'];
            $cts_data['settlement_money'] = $third_settlement['settlement_money'];
            $cts_data['amount_money'] = $third_settlement['amount_money'];
            $cts_data['fee'] = $third_settlement['fee'];
            $cts_data['add_ip'] = request()->ip();
            $cash_third_settle_id = CashThirdsettleModel::insertGetId($cts_data);

            $data = [
                'shop_id'=>$this->request->shopId,
                'order_id'=>$order_id,
                'third_settlement_id' => $third_settlement_id,
                'cash_third_settle_id' => $cash_third_settle_id,
                'num' => $num,
                'type'=>7,
                'remarks'=>$remarks,
                'operate_id'=>$this->request->accountId,
                'info_type' => ($third_settlement['is_paid_in'] == 1)?1:2
            ];
            CashSettleInfoModel::insertGetId($data);

            Db::commit();

            return $this->success('添加成功');

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
    }
    /**
     * 获取结算信息
     */
    public function settleInfoList(){
        $order_id = $this->request->param('order_id/d',0);

        if($order_id<1) return $this->error('订单不存在');

        $order = GoodsOrderModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'is_delete'=>0])->find();

        if(empty($order)) return $this->error('订单不存在');

        $where['shop_id'] = $this->request->shopId;
        $where['order_id'] = $order_id;

        $field = 'si.settle_info_id,si.type,si.name,si.num,si.money,si.refund_money,s.settlement_name';
        $order = ['si.add_time'=>'asc'];
        $return = CashSettleInfoModel::list($where,$order,$this->request->page,$this->request->limit,$field);

        return $this->success($return);

    }
    /**
     * 退款（包含部分退款）
     */
    public function refundPlatformMoney(){
        $order_id = $this->request->param('order_id/d',0);
        $refund_money = $this->request->param('refund_money/f',0);
        $settle_info_id = $this->request->param('settle_info_id/d',0);
        $refund_type = $this->request->param('refund_type',1);//1全额退款2部分退款
        $reason = $this->request->param('reason');

        if($order_id<1) return $this->error('订单不存在');
        $order = GoodsOrderModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'is_delete'=>0])->find();
        if(empty($order)) return $this->error('订单不存在');
        if(empty($reason)) return $this->error('退款原因不能为空');

        $where['shop_id'] = $this->request->shopId;
        $where['settle_info_id'] = $settle_info_id;
        $where['order_id'] = $order_id;
        $info = CashSettleInfoModel::getById($where);
        if(empty($info)) return $this->error('结算信息不存在');
        if(!in_array($info['type'],[2,3,6])) return $this->error('结算不支持退款');

        if($order['is_settle'] ==1) return $this->error('该订单已结算不能退款');
        if($refund_type==2 && ($refund_money <= 0)) return $this->error('退款金额必须大于0');
        if($refund_money > ($info['money'] - $info['refund_money'])) return $this->error('退款金额大于可退款金额');
        if($refund_type == 2 && $info['money'] == $refund_money) return $this->error('部分退款金额已是全额金额，请选全额退款');
        if($info['money'] == $info['refund_money']) return $this->error('已全部退完');
        if($refund_type == 1 && $info['refund_money']>0) return $this->error('已部分退款');

        $refund_money = $refund_type==1?$info['money']:$refund_money;

        Db::startTrans();
        try{
            if($info['type']==2){
                //修改用户储值卡
                $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $order['member_id']);
                $res = $MemberWalletLogic->rebackBalance($refund_money, 0 , 27);
                if($res == false){
                    return $this->error($MemberWalletLogic->getError());
                }

            }
            if($info['type']==3){
                //修改用户钱包
                $member = MemberModel::where(['member_id'=>$order['member_id']])->find();
                $money = $member->money;
                $member->money = $member->money+$refund_money;
                $member->save();

                LogsLogic::money($this->request->shopId, $order['member_id'], 27, 1, $money,$refund_money, $member->money+$refund_money,0,$order['order_id'],$order['pin_tuan_order_id']);

            }

            //添加退款记录
            $order_refund_data['shop_id'] = $this->request->shopId;
            $order_refund_data['settle_info_id'] = $settle_info_id;
            $order_refund_data['order_id'] = $order_id;
            $order_refund_data['member_id'] = $order['member_id'];
            $order_refund_data['refund_price'] = $refund_money;
            $order_refund_data['remain_money'] = $info['money'] -$info['refund_money'] - $refund_money;
            $order_refund_data['pay_money'] = $info['money'];
            $order_refund_data['status'] = 1;
            $order_refund_data['reason'] = $reason;
            $order_refund_data['refund_type'] = $refund_type;
            $order_refund_data['update_time'] = date('Y-m-d H:i:s');
            $order_refund_data['operate_id'] = $this->request->accountId;
            $order_refund_data['refund_platform_money'] = $info['type']==3?$refund_money:0;
            $order_refund_data['refund_money'] = $info['type']==2?$refund_money:0;
            $order_refund_data['refund_weixin'] = $info['type']==4?$refund_money:0;
            $order_refund_data['refund_xianjin'] = $info['type']==6?$refund_money:0;
            $order_refund_data['origin_type'] = 2;
            OrderRefundModel::insertGetId($order_refund_data);

            //修改订单
            $data['refund_money'] = $info['refund_money'] + $refund_money;
            CashSettleInfoModel::up($data,['settle_info_id'=>$settle_info_id]);

            Db::commit();

            return $this->success('退款成功');

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
    }
    /**
     * 删除结算信息
     */
    public function delSettleInfo(){
        $order_id = $this->request->param('order_id/d',0);
        $settle_info_id = $this->request->param('settle_info_id/d',0);

        if($order_id<1) return $this->error('订单不存在');
        $order = GoodsOrderModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'is_delete'=>0])->find();
        if(empty($order)) return $this->error('订单不存在');
        if($order['status']==8) return $this->error('订单已完成不支持删除');

        $where['shop_id'] = $this->request->shopId;
        $where['settle_info_id'] = $settle_info_id;
        $where['order_id'] = $order_id;
        $info = CashSettleInfoModel::getById($where);
        if(empty($info)) return $this->error('结算信息不存在');
        if(!in_array($info['type'],[7,8,9,10])) return $this->error('结算不支持删除');

        CashSettleInfoModel::up(['is_delete'=>1],['settle_info_id'=>$settle_info_id]);

        return $this->success('删除成功');

    }
    /**
     * 发送短信
     */
    public function sendSms(){
        $member_id = $this->request->param('member_id/d',0);
        $member = MemberModel::where(['member_id'=>$member_id])->find();
        if(empty($member)) return $this->error('用户不存在');

        $code = str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT);

        $params=[
            'code'=>$code,
        ];
        $sms_logic= new SmsLogic();

        $sms_logic->send($this->request->shopId,[$member['mobile']],$params,'useMoneyCode');

        Cache::set('useMoneyCode_'.$member['mobile'],$code,600);

        return $this->success('发送成功');

    }
    /**
     * 验证短信
     */
    public function verifySmsCode(){
        $code = $this->request->param('code');
        $member_id = $this->request->param('member_id/d',0);
        $member = MemberModel::where(['member_id'=>$member_id])->find();
        if(empty($member)) return $this->error('用户不存在');

        $cacheCode=Cache::get('useMoneyCode_'.$member['mobile']);

        if(empty($code) || $code!=$cacheCode){
            return $this->error('验证码错误！请重新输入');
        }

        return $this->success('验证成功');

    }
    /**
     * 账单减免
     */
    public function reduceMoney(){
        $order_id = $this->request->param('order_id/d',0);
        $reduce_money = $this->request->param('reduce_money/f',0);
        $remarks = $this->request->param('remarks');
        $num = $this->request->param('num/d',1);

        if($order_id<1) return $this->error('订单不存在');
        $order = GoodsOrderModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'is_delete'=>0])->find();
        if(empty($order)) return $this->error('订单不存在');

        $data = [
            'shop_id'=>$this->request->shopId,
            'order_id'=>$order_id,
            'name'=>'账单减免',
            'money'=>$reduce_money,
            'num' => $num,
            'type'=>8,
            'remarks'=>$remarks,
            'operate_id'=>$this->request->accountId,
            'info_type' => 2
        ];
        CashSettleInfoModel::insertGetId($data);

        return $this->success('操作成功');
    }
    /**
     * 抹零
     */
    public function intvalMoney(){
        $order_id = $this->request->param('order_id/d',0);
        $num = $this->request->param('num/d',1);

        if($order_id<1) return $this->error('订单不存在');
        $order = GoodsOrderModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'is_delete'=>0])->find();
        if(empty($order)) return $this->error('订单不存在');

        //已付
        $total_pay_money = CashSettleInfoModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'info_type'=>1,'is_delete'=>0])->sum('money');
        $refund_money = CashSettleInfoModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'info_type'=>1,'is_delete'=>0])->sum('refund_money');
        $pay_money = $total_pay_money - $refund_money;
        //优惠
        $youhui_price= CashSettleInfoModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'info_type'=>2,'is_delete'=>0])->sum('money');
        //未支付
        $un_pay_money = sprintf("%.2f",$order['need_pay'] - $pay_money - $youhui_price);

        if($un_pay_money<=0) return $this->error('没有未付金额了');

        $new_money = intval($un_pay_money);
       
        if($un_pay_money - $new_money<=0) return $this->error('不需要抹零');

        $data = [
            'shop_id'=>$this->request->shopId,
            'order_id'=>$order_id,
            'name'=>'账单减免',
            'money'=>$un_pay_money - $new_money,
            'num' => $num,
            'type'=>9,
            'operate_id'=>$this->request->accountId,
            'info_type' => 2
        ];
        CashSettleInfoModel::insertGetId($data);

        return $this->success('账单抹零成功');
    }
    /**
     * 免单
     */
    public function freeMoney(){
        $order_id = $this->request->param('order_id/d',0);
        $type = $this->request->param('type/d',1);//1全免2未支付免单
        $num = $this->request->param('num/d',1);
        $remarks = $this->request->param('remarks');

        if($order_id<1) return $this->error('订单不存在');
        $order = GoodsOrderModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'is_delete'=>0])->find();
        if(empty($order)) return $this->error('订单不存在');

        Db::startTrans();
        try{
            //免全单，需要将已支付的退款
            if($type==1){
                $pay_list= CashSettleInfoModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'info_type'=>1,'is_delete'=>0])->select();
                foreach ($pay_list as $k=>$v){
                    $refund_money = $v['money'] - $v['refund_money'];
                    if($refund_money>0){
                        if($v['type']==2){
                            //修改用户储值卡
                            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $order['member_id']);
                            $res = $MemberWalletLogic->rebackBalance($refund_money, 0 , 27);
                            if($res == false){
                                return $this->error($MemberWalletLogic->getError());
                            }

                        }
                        if($v['type']==3){
                            //修改用户钱包
                            $member = MemberModel::where(['member_id'=>$order['member_id']])->find();
                            $money = $member->money;
                            $member->money = $member->money+$refund_money;
                            $member->save();

                            LogsLogic::money($this->request->shopId, $order['member_id'], 27, 1, $money,$refund_money, $member->money+$refund_money,0,$order['order_id'],$order['pin_tuan_order_id']);

                        }

                        if(in_array($v['type'],[2,3,6])){
                            //添加退款记录
                            $order_refund_data['shop_id'] = $this->request->shopId;
                            $order_refund_data['settle_info_id'] = $v['settle_info_id'];
                            $order_refund_data['order_id'] = $order_id;
                            $order_refund_data['member_id'] = $order['member_id'];
                            $order_refund_data['refund_price'] = $refund_money;
                            $order_refund_data['remain_money'] = $v['money'] -$v['refund_money'] - $refund_money;
                            $order_refund_data['pay_money'] = $v['money'];
                            $order_refund_data['status'] = 1;
                            $order_refund_data['reason'] = $remarks;
                            $order_refund_data['refund_type'] = ($refund_money==$v['money'])?1:2;
                            $order_refund_data['update_time'] = date('Y-m-d H:i:s');
                            $order_refund_data['operate_id'] = $this->request->accountId;
                            $order_refund_data['refund_platform_money'] = $v['type']==3?$refund_money:0;
                            $order_refund_data['refund_money'] = $v['type']==2?$refund_money:0;
                            $order_refund_data['refund_weixin'] = $v['type']==4?$refund_money:0;
                            $order_refund_data['refund_xianjin'] = $v['type']==6?$refund_money:0;
                            $order_refund_data['origin_type'] = 2;
                            OrderRefundModel::insertGetId($order_refund_data);

                            CashSettleInfoModel::up(['refund_money'=>$v['refund_money'] + $refund_money],['settle_info_id'=>$v['settle_info_id']]);
                        }

                        if(in_array($v['type'],[7,8,9,10])){
                            CashSettleInfoModel::up(['is_delete'=>1],['settle_info_id'=>$v['settle_info_id']]);
                        }

                    }

                }
            }

            if($type==2){
                //已付
                $total_pay_money = CashSettleInfoModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'info_type'=>1,'is_delete'=>0])->sum('money');
                $refund_money = CashSettleInfoModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'info_type'=>1,'is_delete'=>0])->sum('refund_money');
                $pay_money = $total_pay_money - $refund_money;
                //优惠
                $youhui_price= CashSettleInfoModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'info_type'=>2,'is_delete'=>0])->sum('money');
                //未支付
                $un_pay_money = sprintf("%.2f",$order['need_pay'] - $pay_money - $youhui_price);

                if($un_pay_money<=0) return $this->error('没有未付金额了');

                $money = $un_pay_money;
            }else{

                $money = $order['need_pay'];
            }

            $data = [
                'shop_id'=>$this->request->shopId,
                'order_id'=>$order_id,
                'name'=>'账单免单',
                'money'=>$money,
                'num' => $num,
                'type'=>10,
                'remarks'=>$remarks,
                'operate_id'=>$this->request->accountId,
                'info_type' => 2
            ];
            CashSettleInfoModel::insertGetId($data);

            Db::commit();

            return $this->success('免单成功');

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
    }
    /**
     * 完成结账
     */
    public function complete(){
        $order_id = $this->request->param('order_id/d',0);

        if($order_id<1) return $this->error('订单不存在');
        $order = GoodsOrderModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'is_delete'=>0])->find();
        if(empty($order)) return $this->error('订单不存在');

        //判断金额是否已大于等于应付金额（结算金额 = 已付-退款+优惠）
        $where['shop_id'] = $this->request->shopId;
        $where['order_id'] = $order_id;
        $where['info_type'] = 1;
        $where['is_delete'] = 0;
        $pay_money = CashSettleInfoModel::where($where)->sum('money');
        $refund_money = CashSettleInfoModel::where($where)->sum('refund_money');
        $where['info_type'] = 2;
        $youhui_money = CashSettleInfoModel::where($where)->sum('money');

        $total_pay_money = $pay_money - $refund_money + $youhui_money;

        $un_pay_money = $order['need_pay'] - $total_pay_money;

        if($total_pay_money<$order['need_pay']) return $this->error('还有未支付金额'.$un_pay_money);
        Db::startTrans();
        try{
            $order->status = 8;
            $order->save();

            if($order['open_table_id']){
                $open_table_ids = explode(',',$order['open_table_id']);
                $ot_where[] = ['open_table_id','in',$open_table_ids];
                $ot_where[] = ['shop_id','=',$this->request->shopId];
                OpenTableModel::up(['status'=>1],$ot_where);
            }
            //删除购物车
            CartModel::up(['is_delete'=>1],['order_id'=>$order_id]);

            Db::commit();

            return $this->success('订单已完成');

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }

    }
}

